<?php


namespace app\api\controller\v32;


use app\api\controller\v2\Auth;
use app\astro\controller\Data;
use app\astro\controller\Planetpower;
use app\astro\controller\Signscore;
use app\common\cachemodel\Astro;
use app\common\cachemodel\Goods;
use app\common\cachemodel\NatalGoods;
use app\common\cachemodel\NatalReport;
use app\common\cachemodel\ZhunleActivity;
use app\common\cachemodel\ZlSynastryReport;
use app\common\lib\ConfigManage;
use app\common\lib\Natal;
use app\common\lib\Util;
use app\common\model\Recode;
use app\web\service\AstroCard;
use app\web\service\AstroExplain;
use think\Env;

/**
 * 星盘星座页面
 * @version 2.6.0
 * Class AstroSign
 * @package app\api\controller\v15
 */
class AstroSign extends Auth
{
    protected $msg;

    /**
     * 本名报告标题配置
     * @var string[]
     */
    protected $natal_title_info = [
        'title' => '格局能力分',
        'title2' => '一生报告',
        'title_intro2' => '点击查看报告详情'
    ];

    /**
     * 获取星座信息
     * @return \think\response\Json
     * @throws \app\common\lib\exception\ApiException
     * @throws \Exception
     */
    public function signInfo()
    {
        $rid = input('param.rid/d', 0);
        $utilModel = new Util();
        if ($this->user && $rid)
        {
            $recode = (new \app\common\cachemodel\Recode())->getInfoById($rid);
            if (!$recode || $recode['uid'] != $this->user['id'])
            {
                return show(config('code.error'), '当前档案不存在');
            }
            if (isset($recode['is_read']) && ($recode['is_read'] === '0' || $recode['is_read'] === 0))
            {
                (new \app\common\cachemodel\Recode())->UpdateData($this->user['id'], $rid, ['is_read' => 1]);
            }
            // $sun = mb_substr($utilModel->recodeAstro($recode['sun']), 0, 2);
            // $moon = mb_substr($utilModel->recodeAstro($recode['moon']), 0, 2);
            // $asc = mb_substr($utilModel->recodeAstro($recode['asc']), 0, 2);
            $host = Env::get('host.domain');
            $oss = Env::get('host.photo');
            $AstroExplain = new AstroExplain();

            if (Util::IsHuawei() && !Util::huaweiIsShowAll())
            {
                $buttons = [
                    [
                        'name' => '星座解读',
                        'icon' => $oss . '/test/index/xzjd.png',
                        'target' => 'link',
                        'link' => $host . '/web/astro_explain_new/index.html?rid=' . $rid . '&need_auth=1'
                    ],
                    [
                        'name' => '幸运之城',
                        'icon' => $oss . '/test/index/xyzc.png',
                        'target' => 'local',
                        'link' => 'acg_map?rid=' . $rid . '&need_auth=1'
                    ]
                ];
            } else
            {
                $buttons = [
                    [
                        'name' => '星座解读',
                        'icon' => $oss . '/test/index/xzjd.png',
                        'target' => 'link',
                        'link' => $host . '/web/astro_explain_new/index.html?rid=' . $rid . '&need_auth=1'
                    ],
                    [
                        'name' => Util::IsHuaweiAndOppo() || Util::CheckAppVersion('2.10.0') !== '小' ? '专业星图' : '专业星盘',
                        'icon' => $oss . '/test/index/zyxp.png',
                        'target' => 'local',
                        'link' => 'astrolable?rid=' . $rid . '&need_auth=1'
                    ],
                    [
                        'name' => '幸运之城',
                        'icon' => $oss . '/test/index/xyzc.png',
                        'target' => 'local',
                        'link' => 'acg_map?rid=' . $rid . '&need_auth=1'
                    ]
                ];
            }
            $data_init = [
                'sign_info' => [
                    'sun_desc' => $AstroExplain->returnIntro(0, explode('-', $recode['sun'])[0]),//太阳描述
                    'moon_desc' => $AstroExplain->returnIntro(1, explode('-', $recode['moon'])[0]),//月亮描述
                    'asc_desc' => $AstroExplain->returnIntro(17, explode('-', $recode['asc'])[0]),//上升描述
                ],
                'button_info' => [
                    'title' => '更多玩法',
                    'buttons' => $buttons
                ],
            ];

            //测自我只有自己的档案时才展示头像框
            if (1 === (int)$recode['isself'])
            {
                $adorn = Util::getUserAdorn($this->user['id']);
                $data = array_merge($data_init, ['avatar_adorn' => $adorn['avatar_adorn']]);
            } else
            {
                $data = $data_init;
            }

            $totalScore = $this->getTotalScore($rid);
            $sign_score = $totalScore['sign_score'];
            $planet_power = $totalScore['planet_power'];
            $new_sign_score = [
                'title' => '星座成分',
                'score' => [],
            ];
            $new_planet_power = [
                'title' => '行星能量',
                'list' => $planet_power,
            ];
            foreach ($sign_score as $value)
            {
                $planet_name = [];
                foreach ($value['in_sign'] as $item)
                {
                    $planet_id = (int)$item['id'];
                    $planet_info = mb_substr($utilModel->PlanetTypeName($planet_id), 0, 1);
                    if ($planet_info === '太')
                    {
                        $planet_info = '日';
                    } elseif ($planet_info === '上')
                    {
                        $planet_info = '升';
                    }
                    $planet_name[] = $planet_info;
                }
                $new_sign_score['score'][] = [
                    'sign_id' => $value['id'],//星座id
                    'planets_name_list' => $planet_name,//行星名称列表
                    'percent' => round($value['percent'], 2),//占比
                    'tags' => $value['tags']//标签
                ];
            }
            $data['sign_score'] = $new_sign_score;
            $data['planet_power'] = $new_planet_power;
            $data['natal_report'] = $this->NatalInfo($rid);

            //星座卡片入口
            $data['sign_card_info'] = [
                'status' => 1,
                'icon' => Env::get('host.photo') . 'test/astro_explain/sign/sign_enter.png',
                'title' => '星座卡片',
                'description' => (new AstroCard())->getUniqueSkillData($recode),
                'target' => 'local',
                'link' => 'astro_card?rid=' . $rid . '&need_auth=1'
            ];
        } else
        {
            if ($this->request->header('version') === '2.5.0' && $this->request->header('app-type') === 'android')
            {
                return show(config('code.error'), '请登录应用后重试');
            }
            return show(config('code.error'), '请退出应用后重试');
        }

        return show(config('code.success'), '获取成功', $data);
    }

    /**
     *  获取人生分数
     * @param int $rid
     * @return array
     * @throws \app\common\lib\exception\ApiException
     * @throws \Exception
     */
    protected function getTotalScore($rid)
    {
        $Data = new Data();
        $map = ['id' => $rid, 'uid' => $this->user['id']];

        $RecodeModel = new Recode();
        $AstroModel = new Astro();

        $userinfo = $RecodeModel->getRecode($map);
        $timestamp1 = $Data->deal_time($userinfo);

        $utdatenow = strftime('%d.%m.%Y', $timestamp1);
        $utnow = strftime('%H:%M:%S', $timestamp1);

        $longitude = ($userinfo['long_deg'] + $userinfo['long_min'] / 60) * $userinfo['ew'];
        $latitude = ($userinfo['lat_deg'] + $userinfo['lat_min'] / 60) * $userinfo['ns'];

        $Data->planets_display = '111111111100100001001';
        $Data->asps_display = [0, 60, 90, 120, 180];
        $Data->asp_orb_all = [0 => 8, 60 => 6, 90 => 7, 120 => 7, 180 => 7, 30 => 1, 150 => 2, 45 => 2, 135 => 2, 72 => 2, 144 => 2];
        $Data->planet_orb_all = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
        $hys = 'p';

        $options = ['utdatenow' => $utdatenow, 'utnow' => $utnow, 'longitude' => $longitude, 'latitude' => $latitude, 'h_sys' => $hys];

        $out = $Data->execData($options);

        $original_data = $Data->getOriginalData($out, $hys);
        $Data->array_remove($original_data, $Data->planets_display);
        $details = $Data->getPlanetHouseDetail($original_data, $original_data['hc1'], $userinfo['year']);

        $phase = $Data->planetPkPlanet($original_data, $original_data, true);
        foreach ($phase['planets'] as $k => $d)
        {
            $details['planets'][$k]['phase'] = $d['phase'];
            if (empty($d['phase'])) $details['planets'][$k]['phase'] = null;
        }

        $details['phase'] = $phase['phase'];
        $details['characteristic'] = $Data->recept_or_mutual_recept($details['planets']);

        $details = $AstroModel->get_structure($details);

        $data = [];
        $SignscoreModel = new Signscore($details);
        $PlanetpowerModel = new Planetpower($details);
        $data['sign_score'] = $SignscoreModel->_initload($rid);
        $data['planet_power'] = $PlanetpowerModel->_initload();
        return $data;
    }

    /**
     * 获取取`本命预测信息
     * @param $rid
     * @return array
     * @throws \Exception
     */
    private function NatalInfo($rid)
    {
        $recodeModel = new Recode();
        $NatalReportModel = new NatalReport();
        if ($rid)
        {
            $recodeInfo = $recodeModel->getRecode(['uid' => $this->user['id'], 'id' => $rid]);
        } else
        {
            $recodeInfo = $recodeModel->getSelfRecode(['uid' => $this->user['id']]);
            $rid = $recodeInfo['id'];
        }
        //  获取分数及词条
        $natal = (new Natal())->getScoreAndText($recodeInfo);
        //  获取本命预测商品信息
        $goodData = (new NatalGoods())->getGoods();
        // 获取合盘报告商品
        if (Util::getSynastryReportSwitch() && Util::CheckAppVersion('2.5.2') !== '小')
        {
            $synastryReportGoods = (new Goods())->GoodsTypeInfo(17);
            $goodData = array_merge($synastryReportGoods, $goodData);
        }
        // 获取解锁订单信息状态
        $unlockReport = $NatalReportModel->getNatalReport2($recodeInfo);
        // $unlockReport = $NatalReportModel->getNatalReport($this->user['id'], $rid);

        $forecast = [];//报告数据
        //长图排序
        $large_unlocking = [];
        $large_active = [];
        $large_unopen = [];
        $large_lock = [];
        $large_unlock = [];
        //短图排序
        $small_unlocking = [];
        $small_active = [];
        $small_unopen = [];
        $small_lock = [];
        $small_unlock = [];
        $bar_sort_index = [];//柱状图排序
        $orderModel = new \app\common\cachemodel\Orders();
        $activingModel = new ZhunleActivity();
        $oldNatalScore = ['feelings' => 'love', 'dating' => 'home', 'carrer' => 'work', 'money' => 'money', 'academic' => 'study'];
        //获取报告商品图片
        $reportImage = ConfigManage::natalReportGoodImage(1);
        $n = 0;
        $largeSortIndex = [0, 2];
        foreach (array_values($goodData) as $key => $item)
        {
            $goodType = (isset($item['good_type']) && $item['good_type'] === 17) ? 17 : 7;
            if ($goodType === 17 && isset($this->headers['app-type']) && $this->headers['app-type'] === 'android' && Util::CheckAppVersion('2.6.0') === '同')
            {
                $largeSortIndex = [1];
                $n++;
                continue;
            }
            if ((int)$item['status'] === 2)//暂不开放状态
            {
                $status = 3;
            } else//判断商品解锁状态
            {
                if ($goodType === 17)
                {   // 合盘报告
                    // 检测 是否购买过
                    $unlockStatus = (new ZlSynastryReport())->getUserHasReportUnlockStatus($this->user['id'], $rid, 0, $item['srid']);
                    $status = $unlockStatus ? 2 : 0;
                } else
                {   // 本命报告
                    if (isset($unlockReport[$item['id']]))
                    {
                        $unlock_status = (int)$unlockReport[$item['id']]['status'] === 2 ? 2 : 1;
                        $status = isset($unlockReport[$item['id']]) ? ($unlock_status) : 0;
                    } else
                    {
                        $status = 0;
                    }
                }
            }

            $is_large = 0;

            if ($goodType === 17)
            {  // 合盘报告
                $is_large = $item['is_large'] ? 1 : 0;
                $bg_img = $item['is_large'] ? $item['bg_img'] : $item['small_bg_img'];
            } else
            {   // 本命报告
                //获取活动商品信息
                $activing = $activingModel->getActivingGood($goodType, $item['id']);
                $actiGids = $activing ? explode(',', $activing['gids']) : [];

                //判断当前图是否为长图
                if (in_array($item['flag'], $reportImage['large_goods'], true))
                {
                    $is_large = 1;
                    $bg_img = $reportImage['large'][$item['flag']];
                } else
                {
                    $bg_img = $reportImage['small'][$item['flag']];
                }

                if (in_array($item['id'], $actiGids, false))
                {
                    $bg_img = $is_large === 1 ? $reportImage['large_active'][$item['flag']] : $reportImage['small_active'][$item['flag']];
                }
            }

            if ($goodType === 17)
            {
                $d = [
                    'score' => $item['score'] ?? 0,
                    'text' => $item['score'] ?? '',
                    'status' => $status,
                    'alert_bg_img1' => $item['alert_bg_img1'] ?? '',
                    'alert_bg_img2' => $item['alert_bg_img2'] ?? '',
                    'bg_img' => $bg_img,
                    'title_img' => $item['title_img'] ?? '',
                    'unlock_num' => $item['base_num'] + $orderModel->getTotalPrepaidOrder($goodType, $item['srid']),
                    'intro' => $item['intro'] ?? '',
                    'gcolor' => $item['color'] ?? '',
                    'gname' => $item['name'] ?? '',
                    'active_time' => 0,
                    'target' => 'local',
                    'link' => $status === 0 ?
                        "synastry_report_detail?rid1={$rid}&rid2=0&srid={$item['srid']}&need_auth=1" :    // 下单介绍页
                        "synastry_report_list?rid1={$rid}&rid2=0&srid={$item['srid']}&need_auth=1"  // 查看合盘报告列表
                ];
            } else
            {
                $d = [
                    // 'gid' => (int)$item['id'],
                    'score' => $natal[$oldNatalScore[$item['flag']]] ?? 0,
                    'text' => $natal[$oldNatalScore[$item['flag']] . '_text'] ?? '',
                    'status' => $status,
                    'alert_bg_img1' => $item['alert_bg_img1'] ?? '',
                    'alert_bg_img2' => $item['alert_bg_img2'] ?? '',
                    'bg_img' => $bg_img,
                    'title_img' => $item['title_img'] ?? '',
                    'unlock_num' => $item['base_num'] + $orderModel->getTotalPrepaidOrder($goodType, $item['id']),
                    'intro' => $item['intro'] ?? '',
                    'gcolor' => $item['color'] ?? '',
                    'gname' => $NatalReportModel->gidName[$item['flag']] ?: '',
//                'active_time' => $item['active_time']
                    'active_time' => 0,
                    'target' => 'local',
                    'link' => "report_details?rid={$rid}&gid={$item['id']}&need_auth=1"
                ];
            }
            $resKey = $key - $n;
            //长图
            if ($is_large)
            {
                if ($status === 1)
                {   // 解锁中
                    $large_unlocking[] = $resKey;
                } elseif ($status === 0 && $d['active_time'] > 0)
                {   // 限时特价 并且 未解锁
                    $large_active[] = $resKey;
                } elseif (!$status)
                {   // 未解锁
                    $large_lock[] = $resKey;
                } elseif ($status === 3)
                {
                    //未开放
                    $large_unopen[] = $resKey;
                } else
                {   // 已解锁
                    $large_unlock[] = $resKey;
                }
            } //短图
            else
            {
                if ($status === 1)
                {   // 解锁中
                    $small_unlocking[] = $resKey;
                } elseif ($status === 0 && $d['active_time'] > 0)
                {   // 限时特价 并且 未解锁
                    $small_active[] = $resKey;
                } elseif (!$status)
                {   // 未解锁
                    $small_lock[] = $resKey;
                } elseif ($status === 3)
                {
                    //未开放
                    $small_unopen[] = $resKey;
                } else
                {   // 已解锁
                    $small_unlock[] = $resKey;
                }
            }
            //柱状图
            if ($goodType !== 17)
            {
                $bar_sort_index[] = $resKey;
            }
            //报告数据
            $forecast[] = $d;
        }
        if (Util::CheckAppVersion('2.10.0') !== '小')
        {
            $this->natal_title_info['title2'] = '深度解读';
        }

        return [
            'title' => $this->natal_title_info['title'],
            'title2' => Util::IsHuaweiAndOppo() ? '节律报告' : $this->natal_title_info['title2'],
            'title_intro2' => $this->natal_title_info['title_intro2'],
            'forecast_list' => $forecast,
            'large_sort_index' => Util::CheckAppVersion('2.5.2') !== '小' ? $largeSortIndex : array_merge($large_unlocking, $large_unlock, $large_active, $large_lock, $large_unopen), // 合盘报告上线 固定第一个
            'small_sort_index' => array_merge($small_unlocking, $small_unlock, $small_active, $small_lock, $small_unopen),
            'bar_sort_index' => $bar_sort_index
        ];
    }
}
